<!--
    Name: 下载本地文件  demo
-->
<template>
    <div>
        <el-button @click="_getFile">下载</el-button>
        <a ref="down" :href="`${baseDir}/${fileName}`" title="" >{{fileName}}</a>
        
    </div>
</template>

<script>
    import axios from 'axios';
    import CONFIG from '@/config';
    export default {
        data () {
            return {
                fileName: 'test-template2.xlsx',
                baseDir: process.env.NODE_ENV === 'development' ? '' : CONFIG.ROUTER_BASE_URL
            };
        },
        created () {
            
        },
        methods: {
            _getFile () {
                // axios({url: `${CONFIG.ROUTER_BASE_URL}/${this.fileName}`, method: 'get', responseType: 'blob'}).then(res => {
                axios({url: `${this.baseDir}/${this.fileName}`, method: 'get', responseType: 'blob'}).then(res => {
                    this._$download(res);
                });
            },
            _$download ({data, headers, request}) {
                let {status, statusText, responseType} = request;
                let oTarget = this.$refs.down;

                // 兼容IE11
                if (window.navigator.msSaveOrOpenBlob) {
                    try {
                        const blobObject = new Blob([data]);
                        window.navigator.msSaveOrOpenBlob(blobObject, `${this.fileName}`);
                    } catch (e) {
                        console.log(e);
                    }
                    return false;
                }
                if (responseType === 'blob' && status === 200 && data) {
                    let url = window.URL.createObjectURL(new Blob([data]));
                    oTarget.href = url;
                    oTarget.setAttribute('download', `${this.fileName}`);
                    oTarget.click();
                }
            }
        }
    };
</script>